<?php

// @formatter:off
/**
 * @file edit.php
 * @author Alejandro Dario Simi
 * @date $Date: 2014-06-03 03:40:32 +0000 (Tue, 03 Jun 2014) $
 *
 * $Id: edit.php 112 2014-06-03 03:40:32Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/trunk/frontview/actions/rule/dor/edit.php $
 */
// @formatter:on

class ActionControllerRuleDorEdit extends WCActionController {
	//
	// Potected variables.
	/**
	 * @var WCConnection Database pointer shortcut.
	 */
	protected $_db;
	/**
	 * @var string Database tables' prefix shortcut.
	 */
	protected $_dbprefix;
	//
	// Magic methods.
	public function __construct() {
		parent::__construct();
		//
		// Loading shortcuts.
		// @{
		$this->_db = WCConnection::Instance();
		$this->_dbprefix = $this->_db->prefix();
		// @}
	}
	//
	// Public methods.
	public function check() {
		$check = parent::check();

		if($check == WC_HTTPERROR_OK) {
			global $wcProfile;
			global $wcRule;
			global $wcRuleAction;

			if(!$wcProfile->allowedTo(WC_PERM_RULE_EDIT)) {
				global $errno;
				global $error;

				$check = WC_HTTPERROR_FORBIDDEN;
				$errno = $check;
				$error = "You don't have enough priviliges";
			}

			if($check == WC_HTTPERROR_OK && (!$wcRule || !$wcRule->ok())) {
				global $errno;
				global $error;

				$check = WC_HTTPERROR_BAD_REQUEST;
				$errno = $check;
				$error = "Invalid rule";
			}
			if($check == WC_HTTPERROR_OK && (!$wcRuleAction || !$wcRuleAction->ok())) {
				global $errno;
				global $error;

				$check = WC_HTTPERROR_BAD_REQUEST;
				$errno = $check;
				$error = "Invalid rule action";
			}
			if($check == WC_HTTPERROR_OK && ($wcRuleAction->rule()->id() != $wcRule->id())) {
				global $errno;
				global $error;

				$check = WC_HTTPERROR_BAD_REQUEST;
				$errno = $check;
				$error = "Wrong rule action combination";
			}
		}

		return $check;
	}
	//
	// Protected methods.
	protected function editDirectoryCollection() {
		$editted = false;

		global $wcGroup;
		global $wcRule;
		global $wcRuleAction;

		return $editted;
	}
	protected function editDirectoryTag() {
		$editted = false;

		$justClean = false;

		global $wcGroup;
		global $wcRule;
		global $wcRuleAction;
		global $wcUser;
		//
		// Cleaning tag name
		$directoryName = explode(",", $_POST["directory"]);
		foreach($directoryName as $name) {
			$name = trim($name);
			if($name) {
				$directoryName = $name;
				break;
			}
		}
		//
		// Cleaning tag name
		$tagNames = array_filter(explode(",", $_POST["tags"]));
		array_walk($tagNames, function(&$item) {
			$item = trim($item);
		});
		//
		// Loading directory object.
		$directory = WCDirectoriesHolder::I()->itemByNameInGroup($directoryName, $wcGroup);
		$directory = array_shift($directory);
		if(!$directory || !$directory->ok()) {
			$justClean = true;
		}
		//
		// Loading tag objects.
		$tags = array();
		foreach($tagNames as $name) {
			$tag = WCTagsHolder::I()->itemByNameInGroup($name, $wcGroup);
			$tag = array_shift($tag);
			if($tag && $tag->ok()) {
				$tags[] = $tag;
			}
		}
		if(!count($tags)) {
			$justClean = true;
		}
		//
		// Cleaning current configuration @{
		$stmt = null;
		$stmtId = __CLASS__."::".__FUNCTION__."[clean]";
		if($this->_db->has($stmtId)) {
			$stmt = $this->_db->get($stmtId);
		} else {
			$query = "delete from {$this->_dbprefix}acts_dor\n";
			$query .= "where      act_rule   = :rule\n";
			$query .= " and       act_group  = :group\n";
			$query .= " and       act_action = :action\n";

			$stmt = $this->_db->prepare($stmtId, $query);
		}
		$params = array(
			":rule" => $wcRule->id(),
			":group" => $wcGroup->id,
			":action" => $wcRuleAction->id()
		);
		$stmt->execute($params);
		// @}

		if(!$justClean) {
			$stmt = null;
			$stmtId = __CLASS__."::".__FUNCTION__."[TAGGER-SET]";
			if($this->_db->has($stmtId)) {
				$stmt = $this->_db->get($stmtId);
			} else {
				$query = "insert\n";
				$query .= "        into {$this->_dbprefix}acts_dor (\n";
				$query .= "                act_rule, act_group, act_action, act_tag, act_directory, act_user)\n";
				$query .= "        values (:rule, :group, :action, :tag, :directory, :user)\n";

				$stmt = $this->_db->prepare($stmtId, $query);
			}

			foreach($tags as $tag) {
				$params = array(
					":rule" => $wcRule->id(),
					":group" => $wcGroup->id(),
					":action" => $wcRuleAction->id(),
					":tag" => $tag->id(),
					":directory" => $directory->id(),
					":user" => $wcUser->id()
				);
				$stmt->execute($params);
			}

			$wcRuleAction->setValidPreviews(false);
			$wcRuleAction->reload();

			$editted = true;
		} elseif(!$directoryName && !count($tags)) {
			$editted = true;
		}




		return $editted;
	}
	protected function loadInfo() {
		//
		// Loading global pointers.
		global $wcRule;
		global $wcRuleAction;

		foreach(WCViewInfoFactory::LoadInfo($wcRule) as $key => $value) {
			eval("\$this->_manager->info_rule_{$key} = \$value;");
		}
		foreach(WCViewInfoFactory::LoadInterfacesInfo($wcRule) as $key => $value) {
			eval("\$this->_manager->info_rule_{$key} = \$value;");
		}
		WCViewInfoFactory::LoadInfo($wcRuleAction, true);

		$auxDir = $wcRuleAction->directory();
		if($auxDir && $auxDir->ok()) {
			$this->_manager->directory_id = $auxDir->id();
			$this->_manager->directory_name = $auxDir->name();
		}

		$auxCol = $wcRuleAction->collection();
		if($auxCol && $auxCol->ok()) {
			$this->_manager->collection_id = $auxCol->id();
			$this->_manager->collection_name = $auxCol->name();
		}

		$tags = array();
		foreach($wcRuleAction->tags() as $tag) {
			$tags[] = array(
				"id" => $tag->id(),
				"name" => $tag->name()
			);
		}
		$this->_manager->tags = $tags;

		$this->_manager->action_status = $wcRuleAction->status;
	}
	protected function resetName() {
		global $wcRuleAction;

		$wcRuleAction->setName(trim($_POST["name"]));
	}
	protected function subRun() {
		$ok = true;
		//
		// Loading global pointers.
		global $wcRule;
		global $wcRuleAction;

		$this->_manager->PATH = "Action Edit: '{$wcRuleAction->name()}' of rule '{$wcRule->name()}'";

		$this->loadInfo();

		return $ok;
	}
	protected function subRunPOST() {
		$ok = true;

		global $wcRuleAction;

		if($wcRuleAction->name() != $_POST["name"]) {
			$this->resetName();
		}
		if($wcRuleAction->status != $_POST["status"]) {
			$wcRuleAction->status = $_POST["status"];
		}

		$mode = $wcRuleAction->mode;
		if($mode == $_POST["mode"]) {
			switch($_POST["mode"]) {
				case "CMOVE":
				case "COLLECTOR":
					$this->_manager->status = $this->editDirectoryCollection();
					break;
				case "MOVE":
				case "TAGGER":
				case "VMOVE":
					$this->_manager->status = $this->editDirectoryTag();
					break;
				default:
					$this->_manager->status = false;
					$this->_manager->status_message = $this->tr("message_unknown_mode");
					break;
			}
		} else {
			$this->_manager->status = false;
			$this->_manager->status_message = $this->tr("message_unknown_error");
		}
//DEBUG
//		$this->_manager->status = false;
//		$this->_manager->status_message = $this->tr("message_unknown_error");
//DEBUG

		return $ok;
	}
}
